<template>
  <van-popup
    v-model:show="visibleComputed"
    position="top"
    :style="{ height: '35%' }"
  >
    <div
      class="px-6 xl:px-0 xl:w-[1280px] xl:m-auto flex flex-col justify-center h-full"
    >
      <input
        type="text"
        placeholder="搜索"
        class="h-24 border-b-4 border-b-black border-solid text-5xl"
      />
      <div class="text-lg text-gray-400 mt-3">点击进入搜索或按ESC关闭</div>
    </div>
  </van-popup>
</template>

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    visible: boolean;
  }>(),
  { visible: false }
);

const { visible } = toRefs(props);

const $emits = defineEmits<{
  "update:visible": [visible: boolean];
}>();
const visibleComputed = computed({
  get() {
    return visible.value;
  },
  set(_val: boolean) {
    $emits("update:visible", _val);
    if (_val) {
      addEscKeydownEvt();
    } else {
      removeEscKeydownEvt();
    }
  },
});

function onEscKeydown(event: KeyboardEvent) {
  if (event.key === "Escape") {
    visibleComputed.value = false;
  }
}
function addEscKeydownEvt() {
  if (process.client) {
    removeEscKeydownEvt();
    document.addEventListener("keydown", onEscKeydown);
  }
}
function removeEscKeydownEvt() {
  if (process.client) {
    document.removeEventListener("keydown", onEscKeydown);
  }
}
onMounted(() => {
  addEscKeydownEvt();
});
onBeforeUnmount(() => {
  removeEscKeydownEvt();
});
</script>

<style scoped></style>
